package com.company.poker.channel.decoder;

import com.company.poker.protocol.AddresseeType;
import com.company.poker.protocol.ByteMessage;
import com.company.poker.protocol.MessageType;
import com.company.poker.protocol.ProtocolType;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * Description of class.
 * Created 4/25/13 2:38 PM
 *
 * @author andrey.rodin@playtech.com
 */

public class ByteMessageDecoder extends FrameDecoder {
    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {

        byte protocolType = buffer.readByte();
        byte[] tokenByte = new byte[36];
        buffer.getBytes(1,tokenByte);
        String tokenStr = new String(tokenByte);
        System.out.println(tokenStr);
        buffer.readerIndex(37);
        byte from = buffer.readByte();
        byte to = buffer.readByte();
        long addressId = buffer.readLong();
        short messageType = buffer.readShort();
        byte[] bodyByte = new byte[buffer.readableBytes()];
        buffer.readBytes(bodyByte);
        String body = new String(bodyByte);
        System.out.println(body);


        ByteMessage.Header header = ByteMessage.newHeaderBuilder()
                .setFrom(AddresseeType.getByCode(from))
                .setTo(AddresseeType.getByCode(to))
                .setUserToken(tokenStr)
                .setMessageType(MessageType.getByCode(messageType))
                .setAddressId(String.valueOf(addressId))
                .setProtocolType(ProtocolType.getByCode(protocolType)).build();

        return new ByteMessage(header, body);
    }
}
